package com.yuns.exam.service.impl;

import ch.qos.logback.core.joran.util.beans.BeanUtil;
import cn.hutool.core.collection.ListUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Lists;
import com.yuns.exam.dto.QuestionRandomDto;
import com.yuns.exam.entity.Exam;
import com.yuns.exam.entity.ExamQuestion;
import com.yuns.exam.entity.Question;
import com.yuns.exam.mapper.ExamMapper;
import com.yuns.exam.mapper.ExamQuestionMapper;
import com.yuns.exam.mapper.QuestionMapper;
import com.yuns.exam.req.ExamDoorParam;
import com.yuns.exam.req.ExamDto;
import com.yuns.exam.req.ExamQueryReq;
import com.yuns.exam.service.IExamService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yuns.exam.vo.*;
import com.yuns.util.ListUtils;
import io.netty.util.internal.StringUtil;
import io.swagger.models.auth.In;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import com.yuns.web.param.FrontPage;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.sql.Wrapper;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2020-10-25
 */
@Service
public class ExamServiceImpl extends ServiceImpl<ExamMapper, Exam> implements IExamService {

    @Resource
    private QuestionMapper questionMapper;

    @Resource
    private ExamQuestionMapper examQuestionMapper;

    @Resource
    private ExamMapper examMapper;

    @Override
    public Object selectExamList(FrontPage frontPage) {
        if (!frontPage.is_search()) {
            return baseMapper.selectExamList(frontPage);
        }
        Page<ExamLibVo> page = new Page<>(frontPage.getPageNumber(), frontPage.getPageSize());
        List<ExamLibVo> list = baseMapper.selectExamList(page, frontPage);
        return page.setRecords(list);
    }

    @Override
    public List<HashMap<String, Object>> selectList(HashMap map) {
        return baseMapper.selectList(map);
    }

    @Override
    @Transactional
    public boolean insertExamData(ExamDto examDto) {
        Exam exam = examDto.getExam();
        //  0：试题创建 1（题库） 通过题目生成
        // 计算总分和及格分 60%   四舍五入整数
        Integer totalGrade = 0;
        if(examDto.getQuestionNum0() != null &&
                examDto.getQuestionScore0()!=null ){
            totalGrade+=examDto.getQuestionNum0()*examDto.getQuestionScore0();
        }
        if(examDto.getQuestionNum1() != null &&
                examDto.getQuestionScore1()!=null ) {
            totalGrade+=examDto.getQuestionNum1() * examDto.getQuestionScore1();
        }
        if(examDto.getQuestionNum2() != null &&
                examDto.getQuestionScore2()!=null ) {
            totalGrade+=examDto.getQuestionNum2() * examDto.getQuestionScore2();
        }
        if(examDto.getQuestionNum3() != null &&
                examDto.getQuestionScore3()!=null ) {
            totalGrade+=examDto.getQuestionNum3() * examDto.getQuestionScore3();
        }

        Long passGrade = Math.round(totalGrade*0.6);
        exam.setGrade(String.valueOf(totalGrade));
        exam.setPassGrade(String.valueOf(passGrade));
        exam.setQuestionSource(0);
        Exam exam1 = Exam.builder().build();
//        exam1 = BeanUtil.copy(q, Exam.class);
        if(exam.getId() == null || StringUtil.isNullOrEmpty(String.valueOf(exam.getId()))) {
            baseMapper.insert(exam);
        }else{
            baseMapper.updateById(exam);
            //删除试卷之前选的题目
            HashMap paramMap = new HashMap();
            paramMap.put("exam_id",exam.getId());
            examQuestionMapper.deleteByMap(paramMap);
        }

        List<Exam> examList = examDto.getQuestionLibs();//题库列表
        List<Long> examIds = Lists.newArrayList();
        examList.forEach(eq->{
            examIds.add(eq.getId());
        });

        for(int i =0 ;i<4;i++) {
            if(examDto.getQuestionNum0()!=null) {
                Integer questionNum = i == 0 ? examDto.getQuestionNum0() : i == 1 ? examDto.getQuestionNum1() :
                        i == 2 ? examDto.getQuestionNum2() : i == 3 ? examDto.getQuestionNum3() : 0;

                Integer  questionScore = i == 0 && examDto.getQuestionScore0()!=null ? examDto.getQuestionScore0() :
                         i == 1 && examDto.getQuestionScore1()!=null ? examDto.getQuestionScore1() :
                        i == 2  && examDto.getQuestionScore2()!=null ? examDto.getQuestionScore2() :
                                i == 3 && examDto.getQuestionScore3()!=null ? examDto.getQuestionScore3() : null;
                if (questionNum != 0) {
                    Question t = Question.builder().
                            questionNum(questionNum).examIds(examIds).questionTypeSel(i).build();
                    List<QuestionRandomDto> questions1 = examQuestionMapper.selectQuestionListByRandom(t);
                    for(QuestionRandomDto iq: questions1){
//                    questions1.forEach(iq -> {
                        // 试卷对应的题目保存
                        // questionId 可以追溯题目的来源于哪个题库（gt_exam_quesiton 中source为1的）
                        // questionid 是 gt_exam_question 的id 考试的题目 0
                        // questionid 是 gt_question的id 题库的题目 1
                        ExamQuestion t1 = ExamQuestion.builder().questionId(String.valueOf(iq.getId())).questionSource(0).
                                analysis(iq.getAnalysis()).questionAnswerReply(iq.getQuestionAnswerReply()).
                                questionAnswer(iq.getQuestionAnswer()).questionType(iq.getQuestionTypeSel()).
                                examId(String.valueOf(exam.getId())).
                                build();
                        if(questionScore!=null) {
                            t1.setGrade(questionScore);
                        }else{
                            t1.setGrade(iq.getQuestionScore());
                            totalGrade += iq.getQuestionScore();
                        }
                        examQuestionMapper.insert(t1);
                    }
                }
            }

        }
        // 有的题目分数来源原始题目
        passGrade = Math.round(totalGrade*0.6);
        exam.setGrade(String.valueOf(totalGrade));
        exam.setPassGrade(String.valueOf(passGrade));
        baseMapper.updateById(exam);
        return true;
    }

    @Override
    public Object selectExamDataList(ExamQueryReq req) {
        List<ExamVO> examVOS = Lists.newArrayList();
        Page<ExamVO> page = new Page<ExamVO>(req.getPageNumber(), req.getPageSize());
        if (!req.is_search()) {
            examVOS = baseMapper.selectExamDataListWithPage(req);;
        }else {
            examVOS = baseMapper.selectExamDataListWithPage(page, req);
        }

        List<ExamVO> errExamVOs = examQuestionMapper.selectQuestionWrongRate();
        Map<String,List<ExamVO>> bigIntegerListMap = errExamVOs.stream().filter(c->c.getErrorRate()!=null).collect(Collectors.groupingBy(ExamVO::getExamId));

        examVOS.forEach(item->{
            List<ExamVO> examVOS1 =bigIntegerListMap.get(item.getExamId());
            if(null!=examVOS1) {
                ExamVO examVO = examVOS1.get(0);
                item.setErrorRate(examVO.getErrorRate()*100);
                item.setAvgGrade(examVO.getAvgGrade());
                item.setExamStudentCount(examVO.getExamStudentCount());
                item.setMaxGrade(examVO.getMaxGrade());
                item.setMinGrade(examVO.getMinGrade());
            }else{
                item.setErrorRate(0f);
            }
        });
        examVOS.stream().sorted(Comparator.comparing(ExamVO::getErrorRate));

        if(req.getOrderBy() == 0){
            examVOS.stream().sorted(Comparator.comparing(ExamVO::getErrorRate).reversed());
        }
        if (!req.is_search()) {
            return  examVOS;
        }
        return page.setRecords(examVOS);
    }

    /**
     * 查询题库
     * @return
     */
    @Override
    public List<ExamDataVO> selectQuestionLibList() {
        List<ExamDataVO> examList = examMapper.selectQuestionLibList();
        return examList;
    }

    /**
     * 查询题库列表带统计数量
     * @return
     */
    @Override
    public Page<ExamQuestionStatisVO> selectAllExamList(ExamQueryReq req) {
        Page<ExamQuestionStatisVO> page = new Page<>(req.getPageNumber(), req.getPageSize());
        return page.setRecords(examMapper.selectAllExamList(page, req));
    }

    @Override
    public Object getExamListForDoor(ExamDoorParam frontPage) {
        Page<ExamDoorVo> page = new Page<ExamDoorVo>(frontPage.getPageNumber(), frontPage.getPageSize());
        if (!frontPage.is_search()) {
            if(frontPage.getData().getExamStatus() == 0){ //已考
               return page.setRecords(baseMapper.getHasExamListForDoor(frontPage));
            }
            return page.setRecords(baseMapper.getUnExamListForDoor(frontPage));
        }

        if(frontPage.getData().getExamStatus() == 0){ //已考
            return page.setRecords(baseMapper.getHasExamListForDoor(page, frontPage));
        }
        List<ExamDoorVo> list = baseMapper.getUnExamListForDoor(page, frontPage);
        return page.setRecords(list);
    }

    @Override
    public List<ExamDetailVO> selectExamDetailList(ExamVO exam) {
        return baseMapper.selectExamDetailList(exam);
    }
}
